package com.frxuexi.park2302.news

import android.app.DatePickerDialog
import android.app.DatePickerDialog.OnDateSetListener
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import android.widget.DatePicker
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.NewsBeanItem
import com.frxuexi.lib_base.http.Const
import com.frxuexi.lib_base.http.GlideUtil
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.park2302.R
import com.frxuexi.park2302.databinding.ActivityNewsAddBinding
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.util.Calendar

@Route(path = "/app/NewsAddActivity")
@AndroidEntryPoint
class NewsAddActivity : BaseActivity<ActivityNewsAddBinding, NewsIntent, NewsViewModel>() {
    override val binding: ActivityNewsAddBinding by lazy {
        ActivityNewsAddBinding.inflate(
            layoutInflater
        )
    }
    override val vm: NewsViewModel by viewModels<NewsViewModel>()
    var type = "园区新闻"

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        ToastUtils.showLong("发布成功")
                        finish()
                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {

        binding.newsaddTitle.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                binding.newsaddNum.setText("${s?.length}/50")
                if (s?.length == 50) {
                    binding.newsaddNum.setTextColor(getColor(R.color.redfont))
                } else {
                    binding.newsaddNum.setTextColor(getColor(R.color.grayfont))
                }
            }

            override fun afterTextChanged(s: Editable?) {
            }

        })
        val uname = SPUtils.getInstance().getString(Const.UNAME, "")
        binding.newsaddPerson.setText(uname)

        binding.newsaddDate.setText(vm.getData(System.currentTimeMillis()))

        binding.newsaddIvdate.setOnClickListener {
            val calendar = Calendar.getInstance()
            DatePickerDialog(
                this,
                object : OnDateSetListener {
                    override fun onDateSet(
                        view: DatePicker?,
                        year: Int,
                        month: Int,
                        dayOfMonth: Int
                    ) {
                        val m = if (month + 1 < 10) "0${month + 1}" else "${month + 1}"
                        val d = if (dayOfMonth < 10) "0${dayOfMonth}" else "${dayOfMonth}"
                        binding.newsaddDate.setText("${year}-${m}-${d}")
                    }
                },
                calendar.get(Calendar.YEAR),
                calendar.get(Calendar.MONTH),
                calendar.get(Calendar.DAY_OF_MONTH)
            ).show()
        }

        val typeList = listOf<String>("园区新闻", "社区新闻")
        val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, typeList)
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.newsaddType.adapter = adapter
        binding.newsaddType.onItemSelectedListener = object : OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                type = typeList[position]
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
            }

        }

        binding.newsaddUpload.setOnClickListener {
            PictureSelector.create(this, PictureSelector.SELECT_REQUEST_CODE).selectPicture()
        }

        binding.newsaddCommit.setOnClickListener {
            val item = NewsBeanItem(
                true,
                binding.newsaddContent.text.toString(),
                null,
                emptyList(),
                binding.newsaddDate.text.toString(),
                true,
                uname,
                binding.newsaddTitle.text.toString(),
                type,0
            )
            vm.sendIntent(NewsIntent.addNews(item))
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PictureSelector.SELECT_REQUEST_CODE && resultCode == RESULT_OK) {
            val bean =
                data?.extras?.getParcelable<PictureBean>(PictureSelector.PICTURE_RESULT)
            GlideUtil.getRoundImg(bean!!.path, binding.newsaddUpload)
        }
    }
}